//
//  CenterViewController.m
//  FloatClouds
//
//  Created by 黄威 on 16/8/25.
//  Copyright © 2016年 黄威. All rights reserved.
//

#import "CenterViewController.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "BaseButton.h"
#import "BaseTextField.h"
#import "SuccessLoginTableViewController.h"
#import "RegisterViewController.h"
#import "TAMacro.h"
#import "ForgetViewController.h"
#import "UMSocial.h"


@interface CenterViewController()
@property (nonatomic, retain) UIImageView *imageViewOfBackGround;
@property (nonatomic, retain) BaseTextField *email;
@property (nonatomic, retain) BaseTextField *password;
@property (nonatomic, retain) NSDictionary *dicOfLoginBack;
@property (nonatomic, assign) NSNumber *statusCode;
@property (nonatomic, copy) NSString *cookie;
@property (nonatomic, copy) NSString *uid;

@end

@implementation CenterViewController



-(void)viewDidLoad{

    [super viewDidLoad];

    [self createLoginView];
    
    [self autoLogin];

}


- (void)autoLogin{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        NSUserDefaults  *Email = [NSUserDefaults standardUserDefaults];
        
        
        if([Email objectForKey:@"email"]){
            
            self.email.text = [Email objectForKey:@"email"];
            
            NSUserDefaults  *Password = [NSUserDefaults standardUserDefaults];
            
            self.password.text = [Password objectForKey:@"password"];
            
            [self login];
        }
        
    });
    
  
}


- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

    self.tabBarController.tabBar.hidden = NO;
    
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil];
    
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    self.navigationItem.title = @"个人中心";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"设置" style:UIBarButtonItemStylePlain target:self action:@selector(setting)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    [self autoLogin];

}

#pragma mark - navigation配置



#pragma mark - 创建登录页基本控件

- (void)createLoginView{

    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 49)];
    [self.view addSubview:imageView];
    imageView.image = [UIImage imageNamed:@"yun"];
    
   
    self.email = [[BaseTextField alloc]init];
    self.email.borderStyle = UITextBorderStyleRoundedRect;
    self.email.clearsOnInsertion=YES;
    UIColor *color = [UIColor whiteColor];
    self.email.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"     请输入您的账号" attributes:@{NSForegroundColorAttributeName: color}];
    self.email.textColor = [UIColor whiteColor];
    self.email.clearButtonMode = UITextFieldViewModeAlways;
    self.email.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.0f];
    self.email.leftViewMode=UITextFieldViewModeAlways;
    self.email.leftView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"小人"]];
    [self.view addSubview:self.email];
    
    
    [self.email mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(40);
        make.right.mas_equalTo(-40);
        make.top.mas_equalTo(100);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.08);
    }];

    
    
    self.password = [[BaseTextField alloc]init];
    self.password.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"     请输入密码" attributes:@{NSForegroundColorAttributeName: color}];
    self.password.textColor = [UIColor whiteColor];
    self.password.secureTextEntry=YES;
    self.password.borderStyle = UITextBorderStyleRoundedRect;
    self.password.clearsOnInsertion=YES;
    self.password.clearButtonMode = UITextFieldViewModeAlways;
    self.password.leftViewMode=UITextFieldViewModeAlways;
    self.password.leftView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"锁头"]];
    self.password.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.0f];
    
    [self.view addSubview:self.password];

    [self.password mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(40);
        make.right.mas_equalTo(-40);
        make.top.mas_equalTo(self.email.mas_bottom).mas_offset(40);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.08);

    }];
    
    
    
    
    BaseButton *loginButton = [BaseButton buttonWithType:UIButtonTypeRoundedRect];
    loginButton.backgroundColor = [UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1];
    [loginButton.layer setMasksToBounds:YES];
    [loginButton.layer setCornerRadius:5.0];
    loginButton.tintColor = [UIColor whiteColor];
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.view addSubview:loginButton];
    [loginButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(80);
        make.right.mas_equalTo(-80);
        make.top.mas_equalTo(self.password.mas_bottom).mas_offset(40);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.07);
    }];
    
    /*65144252*/
    
    BaseButton *registerButton = [BaseButton buttonWithType:UIButtonTypeRoundedRect];
    registerButton.backgroundColor = [UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1];
    [registerButton.layer setMasksToBounds:YES];
    [registerButton.layer setCornerRadius:5.0];
    registerButton.tintColor = [UIColor whiteColor];
    [registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.view addSubview:registerButton];
    [registerButton addTarget:self action:@selector(registerB:) forControlEvents:UIControlEventTouchUpInside];
    [registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(80);
        make.right.mas_equalTo(-80);
         make.top.mas_equalTo(loginButton.mas_bottom).mas_offset(20);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.07);
        
    }];
    
    
    
    BaseButton *forgetButton = [BaseButton buttonWithType:UIButtonTypeRoundedRect];
    [forgetButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [forgetButton.layer setMasksToBounds:YES];
    [forgetButton.layer setCornerRadius:5.0];
    forgetButton.tintColor = [UIColor whiteColor];
    [forgetButton setTitle:@"忘记密码" forState:UIControlStateNormal];
    [self.view addSubview:forgetButton];
    forgetButton.backgroundColor = [UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1];
    
    [forgetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(registerButton.mas_bottom).mas_offset(20);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.2);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.05);
        make.trailing.mas_equalTo(registerButton);
        
    }];
    
    [forgetButton addTarget:self action:@selector(forget:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    BaseButton *QQLOGINBUTTON = [BaseButton buttonWithType:UIButtonTypeRoundedRect];
    [QQLOGINBUTTON setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [QQLOGINBUTTON.layer setMasksToBounds:YES];
    [QQLOGINBUTTON.layer setCornerRadius:self.view.bounds.size.width *0.1];
    QQLOGINBUTTON.tintColor = [UIColor whiteColor];
    [QQLOGINBUTTON setBackgroundImage:[UIImage imageNamed:@"lanseqq"] forState:UIControlStateNormal];
     [self.view addSubview:QQLOGINBUTTON];
    
    
    [QQLOGINBUTTON mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(forgetButton.mas_bottom).mas_offset(20);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.2);
        make.height.mas_equalTo(self.view.mas_width).multipliedBy(0.2);
        make.centerX.mas_equalTo(registerButton);
        
    }];
    
    [QQLOGINBUTTON addTarget:self action:@selector(QQLOGIN) forControlEvents:UIControlEventTouchUpInside];

    
    
    
}

- (void)QQLOGIN{


    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        //          获取微博用户名、uid、token等
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
//            NSDictionary *dict = [UMSocialAccountManager socialAccountDictionary];
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:snsPlatform.platformName];
            NSLog(@"\nusername = %@,\n usid = %@,\n token = %@ iconUrl = %@,\n unionId = %@,\n thirdPlatformUserProfile = %@,\n thirdPlatformResponse = %@ \n, message = %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL, snsAccount.unionId, response.thirdPlatformUserProfile, response.thirdPlatformResponse, response.message);
            
        }});

}


#pragma mark - 按钮点击事件方法

- (void)login{

    
    NSUserDefaults  *Email = [NSUserDefaults standardUserDefaults];
    
    NSString *email = self.email.text;
    
    [Email setObject:email forKey:@"email"];
    
    NSUserDefaults  *Password = [NSUserDefaults standardUserDefaults];
    
    NSString *password = self.password.text;
    
    [Password setObject:password forKey:@"password"];
    
    
    
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSString *postURLstring = @"http://app.yanyue.cn/user/login";
        NSDictionary *parmeters = @{@"password":self.password.text,@"username":self.email.text};
        
        [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        
        
        NSMutableSet *set = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
        [set addObject:@"text/html"];
        [manager.responseSerializer setAcceptableContentTypes:set];
        
        
        // 设置请求POST发送
        [manager POST:postURLstring parameters:parmeters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
        
            self.dicOfLoginBack = responseObject;
            
            self.statusCode = self.dicOfLoginBack[@"status"];
            
            
            
            
          
            if ([self.statusCode integerValue] == 1) {
                
             //   NSLog(@"登录成功");

                
                SuccessLoginTableViewController *successTableViewController = [[SuccessLoginTableViewController alloc]initWithStyle:UITableViewStyleGrouped];
                
                
                //获取COOKIE&UID并完成本地化
                
                NSString *cookie = responseObject[@"cookie"];
                NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *pathCookie = [[path lastObject]stringByAppendingPathComponent:@"cookie.TXT"];
                [cookie writeToFile:pathCookie atomically:YES encoding:NSUTF8StringEncoding error:nil];
                
                
                NSString *uid = responseObject[@"id"];
                NSString *pathUid = [[path lastObject]stringByAppendingPathComponent:@"uid.TXT"];
                [uid writeToFile:pathUid atomically:YES encoding:NSUTF8StringEncoding error:nil];
                
               
                
                //获取数据并通过属性传递至下一页面
                
               
                successTableViewController.name = responseObject[@"name"];
                successTableViewController.photo = responseObject[@"photo"];
                successTableViewController.integral = responseObject[@"integral"];
                successTableViewController.level = responseObject[@"level"];
                successTableViewController.cards = responseObject[@"cards"];
            
                [self.navigationController pushViewController:successTableViewController animated:YES];
                
                
                
                
            }else{
                NSLog(@"登录失败,请检查账号或密码");
                
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"账号或者密码有错误哦" message:nil preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"好的,我重新输入" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    //按钮触发的方法
                }]];
                
                [self presentViewController:alert animated:YES completion:nil];
                
                
            }
            
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           // NSLog(@"请求失败: %@", error);
            
            
            
        }];
        
  

}


#pragma mark - 注册页面

- (void)registerB:(UIButton *)button{
    
    RegisterViewController *registerViewController = [[RegisterViewController alloc]init];
    
      
    [self.navigationController pushViewController:registerViewController animated:YES];

    
}


- (void)forget:(UIButton *)button{
    
    ForgetViewController *forgetViewController = [[ForgetViewController alloc]init];
    
    [self.navigationController pushViewController:forgetViewController animated:YES];
    
 
    
}

#pragma mark - 背景
- (void)creatBackGroundView{

    self.imageViewOfBackGround = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    self.imageViewOfBackGround.image = [UIImage imageNamed:@"灰色布.jpg"];
    
    self.imageViewOfBackGround.alpha = 0.7;
    
    [self.view addSubview:_imageViewOfBackGround];
    
    


   
}


//设置方法事件

- (void)setting{

    [self.email resignFirstResponder];
    [self.password resignFirstResponder];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.email resignFirstResponder];
    [self.password resignFirstResponder];
    
}


@end
